<script setup lang="ts">
import type { FilePreviewProps } from './types';

import { computed } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { spliceSeparator, spliceUrlPrefix } from '#/utils';

const props = withDefaults(defineProps<FilePreviewProps>(), {
  urls: () => [],
  separator: '|',
});

const [Modal, modalApi] = useVbenModal({
  title: '资源',
  onCancel: () => {
    modalApi.close();
  },
  cancelText: '关闭',
  showConfirmButton: false,
});

// 统一处理资源为标准化数组
const normalizedUrls = computed(() => {
  if (!props.urls) return [];

  // 统一转换为字符串数组
  const source =
    typeof props.urls === 'string'
      ? spliceSeparator(props.urls, props.separator)
      : [...props.urls];

  return source
    .map((item) => {
      // 处理可能的嵌套字符串结构
      const strItem = String(item).trim();
      return strItem ? spliceUrlPrefix(strItem) : null;
    })
    .filter(Boolean) as string[]; // 类型断言过滤空值
});
// 提取文件名的函数
function extractFileName(url: string): string {
  const urlParts = url.split('/');
  return decodeURIComponent(urlParts[urlParts.length - 1]);
}
async function openModal() {
  modalApi.open();
}
</script>

<template>
  <div>
    <Modal class="w-[50%]">
      <a-list size="small" bordered :data-source="normalizedUrls">
        <template #renderItem="{ item }">
          <a-list-item>
            <!-- 将文件名作为显示文本，完整路径作为链接 -->
            <a :href="item" target="_blank">{{ extractFileName(item) }}</a>
          </a-list-item>
        </template>
      </a-list>
    </Modal>
    <a-button size="small" type="link" @click="openModal">资源</a-button>
  </div>
</template>
